package cn.com.anypay.manager.controller.sdk;

import cn.com.anypay.manager.service.MapService;
import cn.com.anysdk.map.exception.MapException;
import cn.com.anysdk.map.model.*;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequestMapping("/api/map")
public class MapController {

    @Resource
    private MapService mapService;

    @PostMapping("/switch")
    public String switchProvider(@RequestBody Map<String, Object> config) throws MapException {
        log.info("收到切换地图服务商请求，配置参数: {}", config);
        try {
            String result = mapService.switchProvider(config);
            log.info("切换地图服务商成功: {}", result);
            return result;
        } catch (MapException e) {
            log.error("切换地图服务商失败: {}", e.getMessage(), e);
            throw e;
        }
    }

    @PostMapping("/geocode")
    public LocationResult geocode(@RequestBody String address) throws MapException {
        try {
            String decodedAddress = java.net.URLDecoder.decode(address, "UTF-8");
            log.info("收到地址解析请求，地址: {}", decodedAddress);
            LocationResult result = mapService.geocode(decodedAddress);
            log.info("地址解析成功，结果: {}", result);
            return result;
        } catch (java.io.UnsupportedEncodingException e) {
            log.error("地址解码失败: {}", e.getMessage(), e);
            throw new MapException("Address decoding failed: " + e.getMessage(), e);
        } catch (MapException e) {
            log.error("地址解析失败: {}", e.getMessage(), e);
            throw e;
        }
    }

    @PostMapping("/reverse-geocode")
    public AddressResult reverseGeocode(@RequestBody Location location) throws MapException {
        log.info("收到逆地址解析请求，坐标: {}", location);
        try {
            AddressResult result = mapService.reverseGeocode(location);
            log.info("逆地址解析成功，结果: {}", result);
            return result;
        } catch (MapException e) {
            log.error("逆地址解析失败: {}", e.getMessage(), e);
            throw e;
        }
    }

    @PostMapping("/convert")
    public LocationResult convertCoordinate(
            @RequestBody Location location,
            @RequestParam CoordinateType fromType,
            @RequestParam CoordinateType toType) throws MapException {
        log.info("收到坐标转换请求，原坐标: {}，源坐标系: {}，目标坐标系: {}", location, fromType, toType);
        try {
            LocationResult result = mapService.convertCoordinate(location, fromType, toType);
            log.info("坐标转换成功，结果: {}", result);
            return result;
        } catch (MapException e) {
            log.error("坐标转换失败: {}", e.getMessage(), e);
            throw e;
        }
    }
}
